 
// 导入获取菜单的动作

 
//   // 单击
//  const menu  = useSelector((state:RootState)=>state.auth.menu)
 
// const userInfo:any = useSelector((state:RootState) => state.auth.userInfo );

// 导入useNavigate
import { Outlet, useNavigate ,useLocation} from 'react-router-dom';
// 导入getMenu
import {getMenus,setUserInfo} from '../../store/auth/action'
 
// 导入 useSelector
import { useSelector,useDispatch} from 'react-redux';
// 导入react useState
import React, { useState ,useEffect,useRef} from 'react';
// 导入图标若干
import {
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  UploadOutlined,
  UserOutlined,
  VideoCameraOutlined,
  LogoutOutlined,
  FullscreenOutlined,
  FullscreenExitOutlined,
} from '@ant-design/icons'; 
 
// 导入antd Layout布局 Menu菜单 theme主题
import { Layout, Menu, theme,Tabs } from 'antd';
// 类型导入
import type { Dispatch,State} from '../../store';
import type { MenuItem,UserInfoType } from '../../types/index';

// 通过布局解构 头部，侧边栏，内容
const { Header, Sider, Content } = Layout;

// 定义AdminView组件 React.FC  无状态组件function Component 类型
const AdminView: React.FC = () => {
  // 定义是否全屏状态
  const [isFull, setIsFull] = useState(false);
  const location  =useLocation();
  const dispatch:any= useDispatch();
  // 定义navigate
  const navigate = useNavigate();
  // 定义collapsed状态，setCollapsed方法（控制是否折叠）
  const [collapsed, setCollapsed] = useState(false);
  // 使用theme.useToken()获取主题颜色
  const {
    token: { colorBgContainer },
  } = theme.useToken();  

  // 使用useSelector获取state
   const menuList:MenuItem[] = useSelector((state:State) => state.auth.menu);
   console.log(menuList,"menuList")
  // const menuList:Array<MenuItem> = useSelector((state:State) => state.auth.menuList );
  const userInfo:UserInfoType = useSelector((state:State) => state.auth.userInfo  );
  // console.log(menuList,"menuList")
  // 定义switchMenu方法
  // 定义Item类型 为MenuItem类型的key
  const switchMenu = (item:any) => {
   
    // 如果items中有这个key就不添加，没有则添加
  var list = [...items];
  // 如果key有一个 flag就为真，否则为假 some 如果返回的有一个为真就为真，否则为假
  var flag = list.some((item1) => item1.key === item.key);
  if(!flag){
    // 添加
    list.push({label:item.domEvent.target.innerText,key:item.key})
    // 更新数据
    setItems(list)
  }   
  // 设置选中的key
  setActiveKey(item.key) 
  sessionStorage.setItem("activeKey",item.key)
  sessionStorage.setItem("tabs",JSON.stringify(list))   
    // 跳转页面
  navigate(item.key);
  }
  useEffect(()=>{
    // 没有菜单就获取菜单
    if(menuList.length==0){
       dispatch(getMenus())
    }
    // 默认跳转到dash首页
    
    // 获取本地存储的activeKey
    var activeKey = sessionStorage.getItem("activeKey")||"/admin/dash"
    setActiveKey(activeKey)
    // 获取本地存的tabs
    setItems(JSON.parse(sessionStorage.getItem("tabs")||`[{ "label": "概况",   "key": "/admin/dash" },{"label":"社区团购","key":"/admin/channel/communityPurchase"}]`))
    // 跳转到本地存储的activeKey
    navigate(activeKey)
     
    //本地获取用户信息
    const user = JSON.parse(sessionStorage.getItem("userInfo")||"{}")
    // 放入redux
    dispatch(setUserInfo(user))
  },[])
  // 定义logout方法
  const logout = ()=>{
    // 清除本地存储
    sessionStorage.clear();
    // 跳转到登录页
    navigate("/")
  }
  // 定义全屏方法
  const fullScreen = ()=>{
    if(isFull){
      setIsFull(false)
      // 退出全屏
      document.exitFullscreen()
    }else{
      setIsFull(true)
      // 进入全屏
      document.documentElement.requestFullscreen()
    }
  }
  /**************************tabs***************************** */
type TargetKey = React.MouseEvent | React.KeyboardEvent | string;

  // 默认的tabs
  const defaultPanes =[
      { label: `概况`,   key: "/admin/dash" },
      { label: `添加商品`,   key: "/admin/produce/addProduce" },
  ]
// 默认选中的tabs
  const [activeKey, setActiveKey] = useState(defaultPanes[0].key);
  // tabs的数据
  const [items, setItems] = useState(defaultPanes);
  // tabs的索引
  const newTabIndex = useRef(0);
  // tabs的onChange方法
  const onChange = (key: string) => {
    setActiveKey(key);
    navigate(key)
   
    sessionStorage.setItem("activeKey",key)
  };

  // 添加tabs的方法
  const add = () => {
    const newActiveKey = `newTab${newTabIndex.current++}`;
    setItems([...items, { label: 'New Tab',  key: newActiveKey }]);
    setActiveKey(newActiveKey);
    
  };
  // 移除tabs的方法
  const remove = (targetKey: TargetKey) => {
    // 获取到目标的index
    const targetIndex = items.findIndex((pane) => pane.key === targetKey);
    // 过滤掉需要被删除的tabs
    const newPanes = items.filter((pane) => pane.key !== targetKey);
    // 如果有长度并且目标的key和选中的key相同,并且删除和激活是同一个
    if (newPanes.length && targetKey === activeKey) {
      //  解构key，下标为：如果是最后一个取targetIndex-1,否则就当前删除的下标
      const { key } = newPanes[targetIndex === newPanes.length ? targetIndex - 1 : targetIndex];
      // 更新选中的key
      setActiveKey(key);
      // 跳转到选中的key
      navigate(key)
    }
    setItems(newPanes);
    sessionStorage.setItem("tabs",JSON.stringify(newPanes))
    sessionStorage.setItem("activeKey",activeKey)
  };

  // 编辑的的方法
  const onEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {
    if (action === 'add') {
      add();
    } else {
      remove(targetKey);
    }
  };
 
  /**************************tabsEnd************************** */

  return (
    <Layout className={collapsed?'adminView collapased':'adminView'}>
      <Sider trigger={null} collapsible collapsed={collapsed}>
        <div className="logo" >
          <h3>快团团 {!collapsed&&<span>智能管理</span>}</h3>
        </div>
        <Menu
          onClick={switchMenu}
          theme="dark"
          mode="inline"
          defaultSelectedKeys={['1']}
          items={menuList}
          
        />
      </Sider>
      <Layout className="site-layout">
        <Header style={{ padding: 0, background: colorBgContainer }} className="adminHeader">
          {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
            className: 'trigger',
            onClick: () => setCollapsed(!collapsed),
          })}
          <div className="menu">
            <div className='item' onClick={fullScreen}>
              {
                isFull?<FullscreenExitOutlined className="icon" />:<FullscreenOutlined  className="icon" />
              }
            </div>
            <div className='item'>
              <img src={userInfo.avatar} width="48" className='avatar'/>
            </div>
            <div className='item'>
              <span>{userInfo.name}</span>
            </div>
            <div className='item' onClick={logout}>
            <LogoutOutlined  className="icon"  />
            </div>
          </div>
          
        </Header>
        {/* 内容 */}
        
        <div className='contentWrap'>
        <Tabs
            className='adminTabs'
            hideAdd
            onChange={onChange}
            onTabClick={onChange}
            activeKey={activeKey}
            type="editable-card"
            onEdit={onEdit}
            items={items}
          />
        
        <Content
          style={{
            margin: '24px 16px',
            padding: 24,
            marginTop: 0,
            minHeight: 280,
            background: colorBgContainer,
          }}
        >
          <Outlet />
           
        </Content>
        </div>
      </Layout>
    </Layout>
  );
};

export default AdminView;
   
 